<!-- 红包商城商品信息 -->
<template>
  <div class="table">
    <el-tabs v-model="activeName" @tab-click="handleChangeTabs">
      <el-tab-pane label="商品列表" name="one">
        <!-- <span slot="label"><i class="el-icon-goods"></i> 商品列表</span> -->
        <div class="container">
          <div class="crumbs">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item>
                <el-icon>
                  <Search />
                </el-icon> 查询条件：
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <el-row :gutter="10">
            <el-col :xl="6" :lg="6" :md="12" :sm="24" style="margin-bottom:10px">
              <el-select v-model="searchCondition.categoryId" clearable placeholder="请选择分类">
                <el-option v-for="item in state.selectCategoriesList" :key="item.id" :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-col>
            <el-col :xl="6" :lg="6" :md="12" :sm="24" style="margin-bottom:10px">
              <el-input v-model="searchCondition.goods_name" placeholder="请输入商品名称" clearable></el-input>
            </el-col>
            <el-col :xl="6" :lg="6" :md="12" :sm="24" style="margin-bottom:10px">
              <el-input v-model="searchCondition.goods_no" placeholder="请输入货号" clearable></el-input>
            </el-col>
            <el-col :xl="6" :lg="6" :md="12" :sm="24" style="margin-bottom:10px">
              <el-select v-model.trim="searchCondition.status" clearable placeholder="请选择状态" class="">
                <el-option v-for="item in state.selectStatusList" :label="item.dictLabel" :value="item.dictValue"
                  :key="item.id"></el-option>
              </el-select>
            </el-col>
            <el-col :xl="6" :lg="6" :md="12" :sm="24" style="margin-bottom:10px">
              <el-button type="success" :icon="Search" :disabled="disabledbtn" @click="searchInfo">搜索</el-button>
              <el-button type="warning" :icon="Refresh" :disabled="disabledbtn" @click="resetSearch">重置</el-button>
            </el-col>
          </el-row>
          <div class="crumbs">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item> 查询结果：</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="handle-box">
            <el-button type="primary" :icon="Plus" class="mr10" :disabled="disabledbtn" @click="setActiveName('two')">新增
            </el-button>

            <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="batchDelete('deleteMallGoodsInfo')">
              <template #reference>
                <el-button type="danger" :icon="Delete" class="mr10" :disabled="disabledbtn">批量删除
                </el-button>
              </template>
            </el-popconfirm>
            <el-button type="primary" plain :icon="Edit" class="mr10" :disabled="disabledbtn"
              @click="handleBatchUpdatetatus('putOnShelfInfo', 'nowOnShelf')" v-permission="'changeStatus'">批量上架
            </el-button>
            <el-button type="primary" plain :icon="Edit" class="mr10" :disabled="disabledbtn"
              @click="handleBatchUpdatetatus('putOnShelfInfo', 'hasBeenRemoved')" v-permission="'changeStatus'">批量下架
            </el-button>
            <el-button type="primary" plain :icon="Edit" class="mr10" :disabled="disabledbtn"
              @click="handleBatchUpdatetatus('putOnShelfInfo', 'outOfStock')" v-permission="'changeStatus'">批量缺货
            </el-button>
          </div>
          <el-table :data="tableState.tableList" border class="table" ref="multipleTableRef" v-loading="tableLoading"
            :reserve-selection="true" @sort-change="handleSortSearch" @row-dblclick="rowDblclick">
            <el-table-column type="index" align="center"> </el-table-column>
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column prop="goods_image" label="图片" width="150" align="center">
              <template #default="scope">
                <el-image style="width: 60px; height: 60px" :src="imageUrl + scope.row.goods_image">
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="goods_name" label="商品名称" align="center" :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column prop="goods_no" label="货号" align="center">
            </el-table-column>
            <el-table-column prop="title" label="分类" align="center">
              <template #default="scope">
                <div class="w-tag">
                  <el-tag v-for="(item, index) in scope.row.category" :key="index">{{ item }}</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="stock_total" label="库存" align="center">
            </el-table-column>
            <el-table-column prop="wholesale_price" label="批发价" align="center">
            </el-table-column>
            <el-table-column prop="retail_price" label="零售价" align="center">
            </el-table-column>
            <el-table-column prop="sales_actual" label="销售量" align="center">
            </el-table-column>
            <el-table-column prop="sort" label="排序" align="center" sortable="custom">
              <template #default="scope">
                <div class="">
                  <el-input v-model.trim.number="scope.row.sort" placeholder="请输入内容"
                    @change="handleSort(scope.row)"></el-input>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="statusName" label="状态" align="center">
              <template #default="scope">
                <div class="w-tag">
                  <el-tag
                    :type="scope.row.status === 'nowOnShelf' ? 'success' : scope.row.status === 'outOfStock' ? 'warning' : scope.row.status === 'hasBeenRemoved' ? 'danger' : ''">
                    {{ statusObj[scope.row.status] }}</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center">
              <template #default="scope">
                <el-button type="primary" size="small" text :icon="View" @click="handleViewEdit(scope.row, 'view')">
                  查看
                </el-button>
                <el-button type="primary" size="small" text :icon="Edit" v-permission="'edit'"
                  @click="handleViewEdit(scope.row, 'edit')">
                  编辑
                </el-button>
                <el-button type="primary" size="small" text :icon="Edit" :disabled="scope.row.status === 'nowOnShelf'"
                  v-permission="'changeStatus'" class="cyan"
                  @click="handleUpdatetatus(scope.row, 'putOnShelfInfo', 'nowOnShelf')">
                  上架
                </el-button>
                <el-button type="primary" size="small" text :icon="Edit"
                  :disabled="scope.row.status === 'hasBeenRemoved'" v-permission="'changeStatus'" class="red"
                  @click="handleUpdatetatus(scope.row, 'putOnShelfInfo', 'hasBeenRemoved')">
                  下架
                </el-button>
                <el-button type="primary" size="small" text :icon="Edit" :disabled="scope.row.status === 'outOfStock'"
                  v-permission="'changeStatus'" class="orange"
                  @click="handleUpdatetatus(scope.row, 'putOnShelfInfo', 'outOfStock')">
                  缺货
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination background @update:current-page="handleCurrentChange" @update:page-size="handleSizeChange"
              layout="total, sizes, prev, pager, next, jumper" :page-size="searchCondition.size"
              :current-page="searchCondition.current" :page-sizes="pageSizes" :total="total"
              :hide-on-single-page="false">
            </el-pagination>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="商品详情" name="two">
        <!-- <span slot="label"><i class="el-icon-tickets"></i> 商品详情</span> -->
        <div class="container">
          <el-form ref="mallGoodsFormRef" :model="mallGoodsForm" :rules="rules" v-loading="formLoading"
            label-width="150px">
            <el-divider content-position="left"><span class="title-left-color">基本信息</span></el-divider>
            <el-row :gutter="10">
              <el-col :span="9">
                <el-form-item label="商品分类：" prop="category_ids">
                  <el-select v-model="mallGoodsForm.category_ids" multiple placeholder="请选择分类">
                    <el-option v-for="item in state.selectCategoriesList" :key="item.id" :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="1">
                <el-button type="primary" plain
                  @click="getListDataInfo('getMallCategoryInfo', state, 'selectCategoriesList')">刷新</el-button>
              </el-col>
              <el-col :span="10">
                <el-form-item label="商品名称：" prop="goods_name">
                  <el-input v-model.trim="mallGoodsForm.goods_name" maxlength=50 placeholder="商品名称">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="10">
                <el-form-item label="商品状态：" prop="status">
                  <el-select v-model.trim="mallGoodsForm.status" placeholder="请选择状态" class="">
                    <el-option v-for="item in state.selectStatusList" :label="item.dictLabel" :value="item.dictValue"
                      :key="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="9">
                <el-form-item label="运费模板：" prop="deliver_id">
                  <el-select v-model.trim="mallGoodsForm.deliver_id" placeholder="请选择运费模板" filterable class="">
                    <el-option v-for="item in state.selectFreighTemplateList" :label="item.deliver_name"
                      :value="item.id" :key="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="1">
                <el-button type="primary" plain
                  @click="getListDataInfo('getMallDeliverInfo', state, 'selectFreighTemplateList')">刷新</el-button>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="5">
                <el-form-item label="成本价：" prop="cost_price">
                  <el-input v-model.trim="mallGoodsForm.cost_price" maxlength=11 placeholder="请输入成本价">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="批发价：" prop="wholesale_price">
                  <el-input v-model.trim="mallGoodsForm.wholesale_price" placeholder="请输入批发价">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="零售价：" prop="retail_price">
                  <el-input v-model.trim="mallGoodsForm.retail_price" placeholder="请输入零售价">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="10">
                <el-form-item label="货号：" prop="goods_no">
                  <el-input v-model.trim="mallGoodsForm.goods_no" placeholder="请输入货号">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="是否使用货号：" prop="platform_type">
                  <el-select v-model.trim="mallGoodsForm.is_goods_no" clearable placeholder="请选择" class="">
                    <el-option v-for="item in state.selectWhetherListSearch" :label="item.dictLabel"
                      :value="item.dictValue" :key="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="10">
                <el-form-item label="排序：" prop="sort">
                  <el-input v-model.trim.number="mallGoodsForm.sort" placeholder="请输入排序">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="发布平台：" prop="platform_type">
                  <el-select v-model.trim="mallGoodsForm.platform_type" clearable multiple placeholder="请选择发布的平台"
                    class="">
                    <el-option v-for="item in state.selectPlatformList" :label="item.dictLabel" :value="item.dictValue"
                      :key="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="10">
                <el-form-item label="商品卖点：" prop="selling_poiont">
                  <el-input type="textarea" placeholder="请输入商品卖点" v-model.trim="mallGoodsForm.selling_poiont"
                    maxlength="60" :rows="3" show-word-limit></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="10">
                <el-form-item label="商品主图：" prop="goods_image">
                  <div class="w-spec w-main-inage">
                    <el-upload class="avatar-uploader" v-if="!mallGoodsForm.goods_image" :action="uploadUrl"
                      :data="resourcesUploadData" :show-file-list="false"
                      :on-success="(response) => handleResourcesUploadSuccess(response, mallGoodsForm, 'goods_image')"
                      :before-upload="(file) => handleBeforeUpload(file)">
                      <el-icon class="avatar-uploader-icon">
                        <Plus />
                      </el-icon>
                    </el-upload>
                    <div class="wzg-continer-img" v-else>
                      <img :src="mallGoodsForm.goods_image === '' ? '' : imageUrl + mallGoodsForm.goods_image" alt="图片"
                        class="wzg-img">
                      <el-icon class="el-icon-close" @click="handleDeleteResources(mallGoodsForm, 'goods_image')">
                        <Close />
                      </el-icon>
                    </div>
                    <p>建议：尺寸100*100,大小200k以下</p>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="20">
                <el-form-item label="商品轮播图片：" prop="goods_images">
                  <div>
                    <div v-for="(item, index) in state.goodsImageList" :key="index" class="w-img-list">
                      <img :src="imageUrl + item" class="w-img" :data-index="index" draggable="true"
                        @dragstart="handleImgDrag" @dragover="handleImgAllowDrop" @drop="handleImgDrop">
                      <div class="w-icon">
                        <el-icon class="w-look-icon" @click="handlePictureCardPreview(item)">
                          <ZoomIn />
                        </el-icon>
                        <el-icon class="w-del-icon" @click="handleRemove(item)">
                          <Delete />
                        </el-icon>
                      </div>
                    </div>
                    <el-upload :action="uploadUrl" multiple v-if="state.goodsImageList.length < 5"
                      list-type="picture-card" class="w-img-upload" :data="uploadData" :show-file-list="false"
                      :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                      <el-icon>
                        <Plus />
                      </el-icon>
                    </el-upload>
                    <el-dialog title="查看" width="33%" v-model="loadingDialogImg">
                      <img :src="dialogImageUrl" alt="" style="width:100%" />
                    </el-dialog>
                    <p class="img-desc">
                      建议：尺寸750x750像素以上(等比例亦可)，大小1M以下，最多上传5张
                    </p>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="20">
                <el-form-item label="轮播视频：" prop="goods_video">
                  <div>
                    <el-upload class="avatar-uploader" v-if="!mallGoodsForm.goods_video" :action="uploadUrl"
                      :data="videoUploadData" :show-file-list="false"
                      :on-success="(response) => handleVideoUploadSuccess(response, mallGoodsForm, 'goods_video')"
                      :before-upload="(file) => handleBeforeVideoUpload(file)">
                      <el-icon class="avatar-uploader-icon">
                        <Plus />
                      </el-icon>
                    </el-upload>
                    <div class="wzg-continer-video" v-if="mallGoodsForm.goods_video" title="点击查看">
                      <video :src="imageUrl + mallGoodsForm.goods_video" controls
                        class="avatar cursor--pointer wzg-video"></video>
                      <el-icon class="w-video-del" @click="handleDeleteVideoResources(mallGoodsForm, 'goods_video')">
                        <Delete />
                      </el-icon>
                    </div>
                    <p class="img-desc">
                      建议：上传20s以内的短视频，大小10M以下。只能上传一个视频
                    </p>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="10">

              </el-col>
            </el-row>
            <el-divider content-position="left"><span class="title-left-color">规格信息</span></el-divider>
            <el-row :gutter="10">
              <el-col :span="10">
                <el-form-item label="库存：" prop="stock_total">
                  <el-input v-model.trim.number="mallGoodsForm.stock_total"
                    :disabled="mallGoodsForm.sku_list.length !== 0" maxlength="8" placeholder="请输入库存">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="已售基数：" prop="sales_initial">
                  <el-input v-model.trim.number="mallGoodsForm.sales_initial" maxlength="6" placeholder="请输入已售基数">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10" v-for="(item, index) in state.spec_list" :key="item.id">
              <el-col :span="20">
                <el-form-item :label="item.name + ':'">
                  <div class="ibDraggable" :key="tag.id" v-for="(tag) in item.spec_value" :data-index="index"
                    :data-id="tag.id" draggable="true" @dragstart="handleDrag" @dragover="handleAllowDrop"
                    @drop="handleDrop">
                    <el-tag closable :disable-transitions="false" @close="handleClose(index, item.id, tag.id)">
                      {{ tag.name }}
                    </el-tag>
                  </div>
                  <el-input class="input-new-tag" v-if="item.inputVisible" v-model="item.inputValue"
                    @keyup.enter.native="handleInputConfirm(index, item.id, item.inputValue)"
                    @blur="handleInputConfirm(index, item.id, item.inputValue)">
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(index, item.name)">+
                    新增</el-button>
                  <el-icon class="w-icon-close" @click="handleDeleteSpecName(item.id)">
                    <CircleClose />
                  </el-icon>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="10" v-show="showSpecName">
              <el-col :span="5">
                <el-form-item label="规格名：">
                  <el-input v-model.trim="spec.name" placeholder="请输入规格名">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="1">
                <el-button type="primary" :disabled="disabledbtn" @click="handleConfirmSpecName">确认</el-button>
              </el-col>
              <el-col :span="1">
                <el-button type="primary" plain :disabled="disabledbtn" @click="handleCancelSpecName">取消</el-button>
              </el-col>
            </el-row>
            <el-row :gutter="10" v-show="!showSpecName && state.spec_list.length < 2">
              <el-col :span="10">
                <el-form-item label="">
                  <el-button type="primary" plain @click="handleAddSpecName">添加规格</el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10" v-show="mallGoodsForm.sku_list.length > 0">
              <el-col :span="10">
                <el-form-item label="">
                  <el-button type="primary" plain @click="handleBatchSetUpSpecInfo"> 批量设置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="20">
                <el-form-item label="商品规格：">
                  <el-table :data="mallGoodsForm.sku_list" border class="table" :span-method="handleMergeLine()"
                    :reserve-selection="true">
                    <el-table-column :prop="'w' + item.id" :label="item.name" align="center"
                      v-for="item in state.spec_list" :key="item.id">
                    </el-table-column>
                    <el-table-column prop="goods_sku_no" label="规格货号" align="center">
                      <template #default="scope">
                        <div class="">
                          <el-input v-model.trim="scope.row.goods_sku_no" placeholder="请输入规格货号"></el-input>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column prop="cost_price" label="成本价" align="center">
                      <template #default="scope">
                        <div class="">
                          <el-input v-model.trim="scope.row.cost_price" placeholder="请输入成本价"></el-input>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column prop="wholesale_price" label="批发价" align="center">
                      <template #default="scope">
                        <div class="">
                          <el-input v-model.trim="scope.row.wholesale_price" placeholder="请输入批发价"></el-input>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column prop="retail_price" label="零售价" align="center">
                      <template #default="scope">
                        <div class="">
                          <el-input v-model.trim="scope.row.retail_price" placeholder="请输入零售价"></el-input>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column prop="stock_num" label="库存" align="center">
                      <template #default="scope">
                        <div class="">
                          <el-input v-model.trim.number="scope.row.stock_num" placeholder="请输入库存"
                            @change="handleChangeStockNum"></el-input>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column prop="image" label="图片(默认为主图)" align="center" width="150">
                      <template #default="scope">
                        <div class="w-spec">
                          <el-upload class="avatar-uploader" v-if="!scope.row.image" :action="uploadUrl"
                            :data="uploadData" :show-file-list="false" :on-success="handleSpecImgSuccess(scope.row)"
                            :before-upload="beforeAvatarUploadImg">
                            <el-icon class="avatar-uploader-icon small">
                              <Plus />
                            </el-icon>
                          </el-upload>
                          <div class="wzg-continer-img small" v-else>
                            <img :src="scope.row.image === '' ? '' : imageUrl + scope.row.image" alt="规格图片"
                              class="wzg-img">
                            <el-icon class="el-icon-close" @click="handleDeleteSpecImage(scope.row)">
                              <Close />
                            </el-icon>
                          </div>
                        </div>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form-item>
              </el-col>
            </el-row>

            <el-divider content-position="left"><span class="title-left-color">商品详情</span></el-divider>
            <el-row :gutter="10">
              <el-col :span="20">
                <el-form-item label="商品详情：" class="goods-detail" prop="goods_content">
                  <div style="width: 397px;border: 1px solid #ccc; margin-top: 10px">
                    <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" mode="default"
                      style="border-bottom: 1px solid #ccc" />
                    <Editor :defaultConfig="editorConfig" mode="default" v-model="valueHtml"
                      style="height: 700px; overflow-y: hidden" @onCreated="handleCreated"
                      @onChange="(editor) => handleEditorChange(mallGoodsForm, 'goods_content', editor)" />
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="footer-center">
            <el-button :disabled="disabledbtn" @click="cancelSubmit">返 回</el-button>
            <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn"
              @click="submitForm('commonMallGoodsInfo', getTableInfo, handleValidAssignment)">确
              定
            </el-button>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 批量设置规格信息弹出框 -->
    <el-dialog title="批量设置" v-model="editVisible" width="60%" draggable :close-on-click-modal="closeOnClickModal"
      @closed="closedFormDialog">
      <el-form ref="spacBatchListRef" :model="spacBatchList" label-width="150px">
        <el-row :gutter="10">
          <el-col :span="10">
            <el-form-item label="成本价：" prop="cost_price">
              <el-input v-model.trim="spacBatchList.cost_price" placeholder="成本价">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="批发价：" prop="wholesale_price">
              <el-input v-model.trim="spacBatchList.wholesale_price" placeholder="批发价"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="10">
            <el-form-item label="零售价：" prop="retail_price">
              <el-input v-model.trim="spacBatchList.retail_price" placeholder="零售价">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="库存：" prop="sort">
              <el-input v-model.trim.number="spacBatchList.stock_num" placeholder="库存"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancelSubmit">取 消</el-button>
        <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="handleSubmitForm">确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script setup>
import { reactive, ref, onBeforeUnmount } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { View, Delete, Edit, Search, Plus, Refresh, CircleClose, ZoomIn } from '@element-plus/icons-vue';
import { api as Request, imageUrl, uploadUrl } from '@/utils/api';
import { useTable } from '@/hooks/useTable.js';
import { useTabsForm } from '@/hooks/useTabsForm.js';
import { useSort } from '@/hooks/useSort.js';
import { useDictData } from '@/hooks/network/useDictData.js';
import { useListData } from '@/hooks/network/useListData.js';
import { useUpload } from '@/hooks/useUpload.js';
import useWangeditor from '@/hooks/useWangeditor.js';
import useRules from '@/hooks/useRules.js';

const disabledbtn = ref(false);/*  按钮可用与不可用 */
const formLoading = ref(false);/*  对话框中数据提交加载 */
let { editorRef, valueHtml, toolbarConfig, editorConfig, handleCreated,
  handleEditorChange, handleDestroyEditor, Editor, Toolbar } = useWangeditor();
let { total, pageSizes, multipleTableRef, tableLoading, tableState, searchCondition,
  handleCurrentChange, handleSizeChange, getTableInfo, searchInfo, resetSearch, batchDelete, deleteInfo, rowDblclick } =
  useTable({
    goods_name: '',
    goods_no: '',
    categoryId: '',
    status: '',
    sort: '',
    current: 1,
    size: 10
  }, 'getMallGoodsInfo', disabledbtn);
let { formRef: mallGoodsFormRef, formData: mallGoodsForm, methodType, isDisabledbtn,
  activeName, setActiveName, handleChangeTabs, submitForm, handleClearData: cancelSubmit } = useTabsForm({
    id: '',
    category_ids: [],
    goods_name: '',
    status: '',
    /* 运费模板 */
    deliver_id: '',
    /* 平台类型 */
    platform_type: ['weChatPlatform', 'alipayPlatform', 'appPlatform'],
    /* 商品卖点：暂时不用 */
    selling_poiont: '',

    /* 是否使用商品货号 */
    is_goods_no: '0',

    sku_list: [
      // {
      //   id: '',
      //   goods_sku_id: '' /* 1_2_3 */,
      //   goods_sku_no: '',
      //   image: '',
      //   cost_price: 0,
      //   wholesale_price: 0,
      //   retail_price: 0,
      //   stock_num: 0
      // }
    ],
    cost_price: '',
    wholesale_price: '',
    retail_price: '',

    sales_actual: 0,
    sales_initial: 0,
    stock_total: 0,
    /* 商品主图 */
    goods_image: '',
    goods_images: '',
    goods_video: '',
    goods_content: '',
    goods_no: '',
    sort: 0
  }, disabledbtn, handleCustomOperation, formLoading);
let { handleSort } = useSort('putMallGoodsSortInfo', searchInfo);

const rules = useRules('mallGoodsInfoRules');/* 校验规则 */
let { getDictDataInfo } = useDictData();
let { getListDataInfo } = useListData();

const spacBatchListRef = ref('');
const state = reactive({
  selectStatusList: [],/* 状态数据 */
  selectCategoriesList: [],/* 分类数据 */
  selectFreighTemplateList: [],/* 运费模板数据 */
  selectWhetherListSearch: [],/* 是否排序数据 */
  selectPlatformList: [],/* 平台类型数据 */
  /* 规格名称列表 */
  spec_list: [
    // {
    //   id: '',
    //   name: '',
    //   inputVisible: '',
    //   inputValue: '',
    //   spec_value: [
    //     {
    //       id: '',
    //       name: ''
    //     }
    //   ]
    // }
  ],
  /* 用户存放上传的图片地址 */
  goodsImageList: []
});

/* 商品状态 */
const statusObj = reactive({})

const closeOnClickModal = ref(false);/* 是否可以通过点击 modal 关闭 Dialog */
const showSpecName = ref(false);/* 规格名称相关显示或隐藏	*/
const showSpecValue = ref(false);/* 规格值相关显示或隐藏 */
const editVisible = ref(false);/* 模态框显示隐藏 */
const loadingDialogImg = ref(false);/* 模态框显示隐藏 */

/* 规格名称 */
const spec = reactive({
  name: ''
});
/* 批量修改规格信息 */
const spacBatchList = reactive({
  stock_num: 0,
  retail_price: '',
  wholesale_price: '',
  cost_price: ''
});
const id = ref(-1); /* 删除时所需的编号 删除时的id */
const tempGoodsImageNumber = ref(0); /* 用户存放上传的图片数量 */
const dialogImageUrl = ref(''); /* 图片查看的地址 */

/* 主图 */
let { uploadData: resourcesUploadData,
  handleDeleteResources, handleResourcesUploadSuccess, handleBeforeUpload } = useUpload(formLoading, disabledbtn);

/* 视频 */
let { uploadData: videoUploadData,
  handleDeleteResources: handleDeleteVideoResources,
  handleResourcesUploadSuccess: handleVideoUploadSuccess,
  handleBeforeVideoUpload } = useUpload(formLoading, disabledbtn);


/* 批量修改规格信息 */
const uploadData = reactive({
  token: '',
  key: ''
});


/* 关闭切换标签页以后的自定义操作 */
function handleCustomOperation () {
  mallGoodsForm.id = '';
  /* 清除富文本编辑器中的数据 */
  editorRef.value.clear();
  state.goodsImageList = [];
  mallGoodsForm.sku_list = [];
  tempGoodsImageNumber.value = 0;
  state.spec_list = [];
}

/* 图片 拖拽的目标 */
const handleImgDrag = (e) => {
  let pics = e.currentTarget.dataset.pics;
  let index = e.currentTarget.dataset.index;
  e.dataTransfer.setData('pics', pics);
  e.dataTransfer.setData('index', index);
}
/* 图片 放到何处 阻止默认行为 */
const handleImgAllowDrop = (e) => {
  e.preventDefault();
}
/* 图片 拖拽的目的地 */
const handleImgDrop = (e) => {
  e.preventDefault();
  let index = Number(e.dataTransfer.getData('index'));
  let targetIndex = Number(e.currentTarget.dataset.index);
  if (index !== targetIndex) {
    [state.goodsImageList[index], state.goodsImageList[targetIndex]] =
      [state.goodsImageList[targetIndex], state.goodsImageList[index]]
  }
}

/* 拖拽的目标 */
const handleDrag = (e) => {
  let id = e.currentTarget.dataset.id;
  let index = e.currentTarget.dataset.index;
  e.dataTransfer.setData('id', id);
  e.dataTransfer.setData('index', index);
}
/* 放到何处 阻止默认行为 */
const handleAllowDrop = (e) => {
  e.preventDefault();
}
/* 拖拽的目的地 */
const handleDrop = (e) => {
  e.preventDefault();
  let index = Number(e.dataTransfer.getData('index'));
  let targetIndex = Number(e.currentTarget.dataset.index);
  if (index !== targetIndex) {
    ElMessage.warning('请在同一个规格组中进行排序');
    return;
  }
  let id = Number(e.dataTransfer.getData('id'));
  let targetId = Number(e.currentTarget.dataset.id);

  let value = '';
  let targetValue = '';
  let specValueIndex = '';
  let targetSpecValueIndex = '';

  let sortList = [];

  /* 获取要交换的数据 */
  for (let i = 0; i < state.spec_list[targetIndex].spec_value.length; i++) {
    if (state.spec_list[targetIndex].spec_value[i].id === targetId) {
      targetSpecValueIndex = i;
      targetValue = JSON.parse(
        JSON.stringify(state.spec_list[targetIndex].spec_value[i])
      );
      sortList.push(state.spec_list[targetIndex].spec_value[i].sort);
      break;
    }
  }
  for (let i = 0; i < state.spec_list[index].spec_value.length; i++) {
    if (state.spec_list[index].spec_value[i].id === id) {
      specValueIndex = i;
      value = JSON.parse(
        JSON.stringify(state.spec_list[index].spec_value[i])
      );
      sortList.push(state.spec_list[index].spec_value[i].sort);
      break;
    }
  }
  /* TODO:需要修改 */
  // this.$set(state.spec_list[index].spec_value, specValueIndex, targetValue);
  // this.$set(
  //   state.spec_list[targetIndex].spec_value,
  //   targetSpecValueIndex,
  //   value
  // );

  state.spec_list[index].spec_value[specValueIndex] = targetValue;
  state.spec_list[targetIndex].spec_value[targetSpecValueIndex] = value;

  let sortTempList = [
    {
      id,
      sort: sortList[0]
    },
    {
      id: targetId,
      sort: sortList[1]
    }
  ];
  /* 保存数据 */
  putSpecValueSortInfo(sortTempList);
}

/* 规格值排序 */
const putSpecValueSortInfo = (data) => {
  Request.putSpecValueSortInfo({ spec_value_list: data })
    .then((res) => { })
    .catch((res) => { });
}
/* 确认添加规格名称信息 */
const handleConfirmSpecName = () => {
  for (let i = 0; i < state.spec_list.length; i++) {
    if (state.spec_list[i].name === spec.name) {
      ElMessage.warning('请填写不同的规格名称');
      return;
    }
  }
  showSpecName.value = false;
  /* 请求保存规格名称 */
  commonMallSKUInfo(spec.name);
}
/* 保存规格名称 */
const commonMallSKUInfo = (spec_name) => {
  disabledbtn.value = true;
  formLoading.value = true;
  Request.commonMallSKUInfo({ spec_name })
    .then((res) => {
      state.spec_list.push({
        id: res.result.id,
        name: spec.name,
        inputVisible: false,
        inputValue: '',
        spec_value: []
      });
      spec.name = '';
      handleCancelSpecName();
    })
    .catch((res) => { }).finally(() => {
      disabledbtn.value = false;
      formLoading.value = false;
    });
}
/* 取消添加规格名称信息 */
const handleCancelSpecName = () => {
  showSpecName.value = false;
}
/* 添加规格名称 */
const handleAddSpecName = () => {
  if (
    state.spec_list.length > 0 &&
    state.spec_list[0].spec_value.length === 0
  ) {
    ElMessage.warning(`请先填写${state.spec_list[0].name}的规格值`);
    return;
  }
  showSpecName.value = true;
}
/* 删除某个 规格值 */
const handleClose = (index, spec_list_id, id) => {
  ElMessageBox.confirm('规格值删除后无法取消，确认删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      ElMessage.success('删除成功!');
      /* 删除规格组中对应的规格值信息 */
      for (let i = 0; i < state.spec_list[index].spec_value.length; i++) {
        if (state.spec_list[index].spec_value[i].id === id) {
          state.spec_list[index].spec_value.splice(i, 1);
          break;
        }
      }
      /* 记录规格组中还有几条规格值 */
      let num = state.spec_list[index].spec_value.length;

      /* 如果是多个规格，需要 先取出来，通过_截取，转成数组，判断是否在数组中，在就删除数组中的数据，让后在 _ join成字符串，最好赋值给自己*/
      let i = mallGoodsForm.sku_list.length;
      while (i--) {
        let tempList =
          mallGoodsForm.sku_list[i].goods_sku_id.split('_');
        if (tempList.includes(id + '')) {
          if (tempList.length === 1 || num > 0) {
            mallGoodsForm.sku_list.splice(i, 1);
          } else {
            tempList.splice(tempList.indexOf(id + ''), 1);
            /* 当前只有两个，可以直接赋值，多个就 join*/
            mallGoodsForm.sku_list[i].goods_sku_id =
              tempList.join('_');
            mallGoodsForm.sku_list[i]['w' + spec_list_id] = '';
          }
        }
      }
      /* 如果所有的规格都删除了，并且规格组还有两个以上，那么就只留第一个规格组信息 */
      if (
        mallGoodsForm.sku_list.length === 0 &&
        state.spec_list.length > 1
      ) {
        state.spec_list = [state.spec_list[0]];
      }
      handleChangeStockNum();
    })
    .catch((e) => {
      ElMessage.info('已取消删除');
    });
}
/* 点击新增tag标签 */
const showInput = (index, refs) => {
  state.spec_list[index].inputVisible = true;
  // this.$nextTick(() => {
  //   this.$refs[refs].$refs.input.focus();
  // });
  // this.$refs[refs].$refs.input.focus();
}
/* 删除规格名称 */
const handleDeleteSpecName = (id) => {
  ElMessageBox.confirm('规格名删除后无法取消，确认删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      ElMessage.success('删除成功!');
      /* 删除的规格值id */
      let specValueList = [];
      /* 删除规格组信息 */
      for (let i = 0; i < state.spec_list.length; i++) {
        if (state.spec_list[i].id == id) {
          /* 存储得到对应的规格值ID */
          for (let j = 0; j < state.spec_list[i].spec_value.length; j++) {
            specValueList.push(state.spec_list[i].spec_value[j].id);
          }
          state.spec_list.splice(i, 1);
          break;
        }
      }
      /* 如果只有一个规格组，就直接匹配删除 所有规格列表信息即可 */
      if (state.spec_list.length === 0) {
        mallGoodsForm.sku_list = [];
        return;
      }

      // let list = [];
      /* 当前要删除的规格组中 一个规格的时候，直接修改数据， 两个规格的时候*/
      /* 如果是多个规格，需要 先取出来，通过_截取，转成数组，判断是否在数组中，在就删除数组中的数据，然后在 _ join 转成字符串，最后赋值给自己*/
      for (let i = 0; i < mallGoodsForm.sku_list.length; i++) {
        let tempList =
          mallGoodsForm.sku_list[i].goods_sku_id.split('_');
        for (let j = 0; j < specValueList.length; j++) {
          const _id = specValueList[j] + '';
          if (tempList.includes(_id)) {
            tempList.splice(tempList.indexOf(_id), 1);
            /* 当前只有两个，可以直接赋值，多个就 join*/
            mallGoodsForm.sku_list[i].goods_sku_id =
              tempList.join('_');
            break;
          }
        }
      }
      let list = [];

      /* 此时 去重即可 */
      for (let i = 0; i < mallGoodsForm.sku_list.length; i++) {
        const element = mallGoodsForm.sku_list[i].goods_sku_id;
        if (list.length === 0) {
          list.push(
            JSON.parse(JSON.stringify(mallGoodsForm.sku_list[i]))
          );
        } else {
          let _boolean = false;
          for (let k = 0; k < list.length; k++) {
            let sku_id = list[k].goods_sku_id;
            if (element == sku_id) {
              _boolean = false;
              break;
            } else {
              _boolean = true;
            }
          }
          if (_boolean) {
            list.push(
              JSON.parse(JSON.stringify(mallGoodsForm.sku_list[i]))
            );
          }
        }
      }

      /* 删除所有的规格组id对应的属性名 */
      let i = list.length;
      while (i--) {
        if (list[i]['w' + id] !== undefined) {
          /* 删除对象中的属性  'w'+id */
          delete list[i]['w' + id];
        }
      }

      mallGoodsForm.sku_list = list;

      handleChangeStockNum();
      /* 需要删除 sku_list 中的数据 ，倒删除*/
    })
    .catch((e) => {
      console.log(e);
      ElMessage.info('已取消删除');
    });
}
/* 数组排序 */
const handleSortList = (list) => {
  list = list.sort(function (arr1, arr2) {
    console.log(arr1.goods_sku_id.split('_')[0]);
    console.log(arr2.goods_sku_id.split('_')[0]);
    return (
      Number(arr1.goods_sku_id.split('_')[0]) -
      Number(arr2.goods_sku_id.split('_')[0])
    );
  });
}
/* 失去焦点和enter事件，创建tag标签 */
const handleInputConfirm = (index, spec_id, inputValue) => {
  if (disabledbtn.value) return;
  if (inputValue === '') {
    state.spec_list[index].inputVisible = false;
    return;
  }
  for (let i = 0; i < state.spec_list[index].spec_value.length; i++) {
    if (
      state.spec_list[index].spec_value[i].name ===
      state.spec_list[index].inputValue
    ) {
      ElMessage.warning('请填写不同的规格值');
      return;
    }
  }
  commonmSpecValueInfo(
    spec_id,
    state.spec_list[index].inputValue,
    index
  );
}
/* 保存规格值 */
const commonmSpecValueInfo = (spec_id, spec_value, index) => {
  disabledbtn.value = true;
  formLoading.value = true;
  Request.commonmSpecValueInfo({ spec_id, spec_value })
    .then((res) => {
      handleSKUList(spec_id, spec_value, res, res.result.id, index);
    })
    .catch((res) => { }).finally(() => {
      disabledbtn.value = false;
      formLoading.value = false;
    });
}
/* 规格sku列表的修改 */
const handleSKUList = (spec_id, spec_value, res, goods_sku_id, index) => {
  state.spec_list[index].spec_value.push({
    id: goods_sku_id,
    name: spec_value,
    sort: res.result.sort
  });
  state.spec_list[index].inputVisible = false;
  state.spec_list[index].inputValue = '';

  /* 创建规格信息 */
  /* 如果没有规格，就直接新增，如果有规格就需要编辑或 编辑+新增了 */
  /* goods_sku_id 需要组合 */
  let skuObj = {
    id: '',
    /* 对象的属性不能是数字，所以需要把他改成字符串 */
    /* 用规格id做属性名，用规格值做属性值 */
    ['w' + spec_id]: spec_value,
    goods_sku_id: goods_sku_id + '' /* 1_2_3 */,
    goods_sku_no: '',
    image: '',
    cost_price: mallGoodsForm.cost_price,
    wholesale_price: mallGoodsForm.wholesale_price,
    retail_price: mallGoodsForm.retail_price,
    stock_num: 0
  };

  /* 一组规格 直接push */
  // debugger;
  if (state.spec_list.length === 1) {
    mallGoodsForm.sku_list.push(skuObj);
    handleChangeStockNum();
    return;
  }
  /*  state.spec_list[0].spec_value.length >=
      state.spec_list[1].spec_value.length && */
  if (
    state.spec_list[0].spec_value.length === 1 ||
    state.spec_list[1].spec_value.length === 1
  ) {
    let skuIdListlength =
      mallGoodsForm.sku_list[0].goods_sku_id.split('_').length;
    if (skuIdListlength === 1) {
      /* 修改 goods_sku_id 需要以下划线的方式连接*/
      for (let i = 0; i < mallGoodsForm.sku_list.length; i++) {
        const temp = mallGoodsForm.sku_list[i].goods_sku_id;
        if (index === 0) {
          mallGoodsForm.sku_list[i].goods_sku_id =
            goods_sku_id + '_' + temp;
        } else {
          mallGoodsForm.sku_list[i].goods_sku_id =
            temp + '_' + goods_sku_id;
        }

        /* TODO 新增属性 */
        // $set(
        //   mallGoodsForm.sku_list[i],
        //   'w' + spec_id,
        //   spec_value
        // );
        mallGoodsForm.sku_list[i]['w' + spec_id] = spec_value;
      }
    } else {
      /* 新增 */
      for (let i = 0; i < state.spec_list.length; i++) {
        const element = state.spec_list[i];
        if (i !== index) {
          for (let j = 0; j < state.spec_list[i].spec_value.length; j++) {
            const temp = state.spec_list[i].spec_value[j];
            let tepm_goods_sku_id = '';
            if (index === 0) {
              tepm_goods_sku_id = goods_sku_id + '_' + temp.id;
            } else {
              tepm_goods_sku_id = temp.id + '_' + goods_sku_id;
            }
            let skuObj = {
              id: '',
              /* 对象的属性不能是数字，所以需要把他改成字符串 */
              /* 用规格id做属性名，用规格值做属性值 */
              ['w' + element.id]: temp.name,
              ['w' + spec_id]: spec_value,
              goods_sku_id: tepm_goods_sku_id,
              goods_sku_no: '',
              image: '',
              cost_price: mallGoodsForm.cost_price,
              wholesale_price: mallGoodsForm.wholesale_price,
              retail_price: mallGoodsForm.retail_price,
              stock_num: 0
            };
            mallGoodsForm.sku_list.push(skuObj);
          }
        }
      }
    }

    /* 按照规格组1中的数据进行排序，排序 */
    handleSortList(mallGoodsForm.sku_list);
    handleChangeStockNum();
    return;
  }

  /* 新增 */
  for (let i = 0; i < state.spec_list.length; i++) {
    const element = state.spec_list[i];
    if (i !== index) {
      for (let j = 0; j < state.spec_list[i].spec_value.length; j++) {
        const temp = state.spec_list[i].spec_value[j];
        let tepm_goods_sku_id = '';
        if (index === 0) {
          tepm_goods_sku_id = goods_sku_id + '_' + temp.id;
        } else {
          tepm_goods_sku_id = temp.id + '_' + goods_sku_id;
        }
        let skuObj = {
          id: '',
          /* 对象的属性不能是数字，所以需要把他改成字符串 */
          /* 用规格id做属性名，用规格值做属性值 */
          ['w' + element.id]: temp.name,
          ['w' + spec_id]: spec_value,
          goods_sku_id: tepm_goods_sku_id,
          goods_sku_no: '',
          image: '',
          cost_price: mallGoodsForm.cost_price,
          wholesale_price: mallGoodsForm.wholesale_price,
          retail_price: mallGoodsForm.retail_price,
          stock_num: 0
        };

        mallGoodsForm.sku_list.push(skuObj);
      }
    }
  }

  /* 按照规格组1中的数据进行排序，排序 */
  handleSortList(mallGoodsForm.sku_list);
  handleChangeStockNum();
}
/* 删除规格图片 */
const handleDeleteSpecImage = ({ goods_sku_id }) => {
  for (let i = 0; i < mallGoodsForm.sku_list.length; i++) {
    if (mallGoodsForm.sku_list[i].goods_sku_id === goods_sku_id) {
      mallGoodsForm.sku_list[i].image = '';
      break;
    }
  }
}
/* 获取商品详情数据 */
const getMallGoodsByIdInfo = (id) => {
  Request.getMallGoodsByIdInfo({ id })
    .then((res) => {
      mallGoodsForm.id = res.result.id;
      mallGoodsForm.category_ids = res.result.category_ids;
      mallGoodsForm.goods_name = res.result.goods_name;
      mallGoodsForm.goods_no = res.result.goods_no;
      mallGoodsForm.platform_type = res.result.platform_type;

      mallGoodsForm.cost_price = res.result.cost_price;
      mallGoodsForm.retail_price = res.result.retail_price;
      mallGoodsForm.sales_actual = res.result.sales_actual;
      mallGoodsForm.sales_initial = res.result.sales_initial;
      mallGoodsForm.selling_poiont = res.result.selling_poiont;
      mallGoodsForm.is_goods_no = res.result.is_goods_no;
      mallGoodsForm.stock_total = res.result.stock_total;
      mallGoodsForm.wholesale_price = res.result.wholesale_price;
      mallGoodsForm.goods_content = res.result.goods_content;
      mallGoodsForm.sort = res.result.sort;

      /* 富文本编辑器中添加数据 */
      valueHtml.value = res.result.goods_content;
      mallGoodsForm.goods_image = res.result.goods_image;
      mallGoodsForm.goods_images = res.result.goods_images;

      if (res.result.goods_images !== '') {
        state.goodsImageList = res.result.goods_images.split(',');
      }

      tempGoodsImageNumber.value = state.goodsImageList.length;

      mallGoodsForm.goods_video = res.result.goods_video;

      /* 运费模板 */
      mallGoodsForm.deliver_id = res.result.deliver_id;
      mallGoodsForm.status = res.result.status;

      mallGoodsForm.sku_list = res.result.sku_list;

      state.spec_list = res.result.spec_list.filter((item) => {
        item.inputVisible = false;
        item.inputValue = '';
        return item;
      });
      if (state.spec_list.length > 1) {
        /* 按照规格组1中的数据进行排序，排序 */
        handleSortList(mallGoodsForm.sku_list);
      }
    })
    .catch((res) => { });
}
/* 点击排序 */
const handleSortSearch = ({ column, prop, order }) => {
  console.log(column, prop, order);
  let sort = '';
  if (order === 'ascending') {
    sort = 'asc';
  } else if (order === 'descending') {
    sort = 'desc';
  }
  searchCondition[prop] = sort;
  searchInfo();
}
/* 点击编辑按钮 */
const handleViewEdit = (row, code, name) => {
  if ('view' === code) {
    isDisabledbtn.value = true;
  } else if ('edit' === code) {
    methodType.value = 'PUT';
  }
  /* 商品详情标签页显示 */
  setActiveName('two');
  getMallGoodsByIdInfo(row.id);
}
/* 批量处理 上下架，缺货*/
const handleBatchUpdatetatus = (method, status) => {
  /* 获取选中的数据 */
  let selection = multipleTableRef.value.store.states.selection.value;
  let l = selection.length;
  if (l > 0) {
    /* 获取要批量修改数据的id值数组 (单个与批量删除相同) */
    let idArray = [];
    /* 数据校验 */
    if (status === 'nowOnShelf') {
      for (let i = 0; i < l; i++) {
        if (selection[i].stock_total === 0) {
          ElMessage.warning('有件商品库存为0，不能上架');
          return;
        }
        if (selection[i].goods_images === '') {
          ElMessage.warning('有件商品轮播图片没有上传，不能上架');
          return;
        }
      }
    }
    for (let i = 0; i < length; i++) {
      idArray.push(selection[i].id);
    }
    updateStatus(method, { idArray, status });
  } else {
    ElMessage.warning('请至少选择一条数据');
  }
}
/* 上下架，缺货 */
const handleUpdatetatus = (row, method, status) => {
  /* 判断库存，图片 */
  if (status === 'nowOnShelf') {
    if (row.stock_total === 0) {
      ElMessage.warning('商品库存为0，不能上架');
      return;
    }
    if (row.goods_images === '') {
      ElMessage.warning('商品轮播图片没有上传，不能上架');
      return;
    }
  }

  updateStatus(
    method,
    { idArray: [row.id], status }
  );
}

/* 更新商品状态 */
const updateStatus = (method, data) => {
  disabledbtn.value = true;
  formLoading.value = true;
  Request[method](data)
    .then((res) => {
      /* 当删除成功后，删除对应选中的数据或单个数据 */
      for (let i = 0; i < data.idArray.length; i++) {
        for (let j = 0; j < tableState.tableList.length; j++) {
          if (data.idArray[i] === tableState.tableList[j].id) {
            tableState.tableList[j].status = data.status;
            break;
          }
        }
      }
      ElMessage.success(`数据修改成功`);
      /* 取消选择 */
      multipleTableRef.value.clearSelection();
    })
    .catch((res) => { }).finally(() => {
      disabledbtn.value = false;
      formLoading.value = false;
    });
}
/* 修改规格数量 事件 */
const handleChangeStockNum = () => {
  let num = 0;
  for (let i = 0; i < mallGoodsForm.sku_list.length; i++) {
    num += mallGoodsForm.sku_list[i].stock_num;
  }
  mallGoodsForm.stock_total = num;
}
/* 批量设置规格信息 */
const handleBatchSetUpSpecInfo = () => {
  editVisible.value = true;
  spacBatchList.retail_price = mallGoodsForm.retail_price;
  spacBatchList.wholesale_price = mallGoodsForm.wholesale_price;
  spacBatchList.cost_price = mallGoodsForm.cost_price;
}
/* 关闭新增编辑查看 弹出框事件 */
const closedFormDialog = () => {
  spacBatchList.stock_num = 0;
  spacBatchList.retail_price = '';
  spacBatchList.wholesale_price = '';
  spacBatchList.cost_price = '';

  closeOnClickModal.value = false;
  spacBatchListRef.value.clearValidate();
}
/* 取消批量设置弹框 */
const handleCancelSubmit = () => {
  editVisible.value = false;
}
/* 批量设置规格信息 */
const handleSubmitForm = () => {
  for (let i = 0; i < mallGoodsForm.sku_list.length; i++) {
    mallGoodsForm.sku_list[i].stock_num = spacBatchList.stock_num;
    mallGoodsForm.sku_list[i].retail_price =
      spacBatchList.retail_price;
    mallGoodsForm.sku_list[i].wholesale_price =
      spacBatchList.wholesale_price;
    mallGoodsForm.sku_list[i].cost_price =
      spacBatchList.cost_price;
  }

  /* 批量设置库存 */
  mallGoodsForm.stock_total =
    mallGoodsForm.sku_list.length * spacBatchList.stock_num;

  handleCancelSubmit();
}
/* 列合并 */
const handleMergeLine = () => {
  let mergeLineList = [];
  /* 做一个统计，要做哪行合并，合并多少条数据 */
  if (state.spec_list.length > 1) {
    for (let i = 0; i < mallGoodsForm.sku_list.length; i++) {
      let skuIdList =
        mallGoodsForm.sku_list[i].goods_sku_id.split('_');
      let _boolean = true;
      for (let j = 0; j < mergeLineList.length; j++) {
        if (mergeLineList[j].id === skuIdList[0]) {
          _boolean = false;
          if (mergeLineList[j].num === 0) {
            mergeLineList[j].num++;
          }
          mergeLineList[j].num++;
          let mergeLine = {
            id: skuIdList[0],
            num: 0
          };
          mergeLineList.push(mergeLine);
          break;
        } else {
          _boolean = true;
        }
      }
      if (_boolean) {
        let mergeLine = {
          id: skuIdList[0],
          num: 0
        };
        mergeLineList.push(mergeLine);
      }
    }
  }
  /* 如果第一项是 num: 0的 情况，要修改为1 */
  console.log(mergeLineList);
  if (mergeLineList.length > 0 && mergeLineList[0].num === 0) {
    for (let i = 0; i < mergeLineList.length; i++) {
      if (mergeLineList[i].num === 0) {
        mergeLineList[i].num = 1;
      }
    }
  }

  return ({ row, column, rowIndex, columnIndex }) => {
    let skuIdList = row.goods_sku_id.split('_');
    if (columnIndex === 0) {
      /* 在此之前，需要分组，相同的数据放到同一行 */
      /* rowspan占领几行，colspan占领几列 */
      // includeList.push(skuIdList[0]);
      if (state.spec_list.length > 1) {
        return {
          rowspan: mergeLineList[rowIndex].num,
          colspan: mergeLineList[rowIndex].num === 0 ? 0 : 1
        };
      } else {
        return {
          rowspan: 1,
          colspan: 1
        };
      }
    }
  };
}
/* 校验数据 */
const handleVerifyData = (params) => {
  /* 有规格名称，必须要有规格值 */
  if (state.spec_list.length !== 0) {
    for (let i = 0; i < state.spec_list.length; i++) {
      const element = state.spec_list[i];
      if (element.spec_value.length === 0) {
        ElMessage.warning(`请填写${element.name}规格值`);
        return false;
      }
    }
  }

  if (isNaN(Number(mallGoodsForm.cost_price))) {
    ElMessage.warning(`请正确填写的成本价的格式`);
    return false;
  }
  if (isNaN(Number(mallGoodsForm.wholesale_price))) {
    ElMessage.warning(`请正确填写的批发价的格式`);
    return false;
  }
  if (isNaN(Number(mallGoodsForm.retail_price))) {
    ElMessage.warning(`请正确填写的零售价的格式`);
    return false;
  }

  if (Number(mallGoodsForm.cost_price) <= 0) {
    ElMessage.warning(`成本价需大于0`);
    return false;
  }
  if (Number(mallGoodsForm.wholesale_price) <= 0) {
    ElMessage.warning(`批发价需大于0`);
    return false;
  }
  if (Number(mallGoodsForm.retail_price) <= 0) {
    ElMessage.warning(`零售价需大于0`);
    return false;
  }

  if (
    Number(mallGoodsForm.cost_price) >
    Number(mallGoodsForm.wholesale_price)
  ) {
    ElMessage.warning(`成本价必须小于批发价`);
    return false;
  }
  if (
    Number(mallGoodsForm.cost_price) >
    Number(mallGoodsForm.retail_price)
  ) {
    ElMessage.warning(`成本价必须小于零售价`);
    return false;
  }
  if (
    Number(mallGoodsForm.wholesale_price) >
    Number(mallGoodsForm.retail_price)
  ) {
    ElMessage.warning(`批发价必须小于零售价`);
    return false;
  }
  return true;
}
/* 新增修改之前修改数据 */
const handleChangeData = () => {
  if (mallGoodsForm.stock_total === 0) {
    mallGoodsForm.status = 'outOfStock';
  }
  /* 格式化轮播图片 */
  mallGoodsForm.goods_images = state.goodsImageList.join(',');
  if (state.goodsImageList.length === 0) {
    mallGoodsForm.status = 'hasBeenRemoved';
  }
}
/* 保存与编辑 前的自定义校验或赋值操作 */
const handleValidAssignment = () => {
  /* 校验数据 */
  if (!handleVerifyData()) return;

  handleChangeData();
}



/* 查看图片 */
const handlePictureCardPreview = (file) => {
  loadingDialogImg.value = true;
  dialogImageUrl.value = imageUrl + file;
}
/* 文件列表移除文件时的钩子 */
const handleRemove = (file) => {
  formLoading.value = false;
  console.log(file);
  formatImg(file);
}
/* 格式化图片 */
const formatImg = (file) => {
  for (let i = 0; i < state.goodsImageList.length; i++) {
    const element = state.goodsImageList[i];
    if (element === file) {
      state.goodsImageList.splice(i, 1);
      tempGoodsImageNumber.value--;
      break;
    }
  }
}
/* 图片上传成功 */
const handleAvatarSuccess = (response) => {
  formLoading.value = false;
  disabledbtn.value = false;
  /* 判断一下是否有相同的图片 */
  for (let i = 0; i < state.goodsImageList.length; i++) {
    if (state.goodsImageList[i] === response.key) {
      ElMessage.warning('请上传不同的图片');
      tempGoodsImageNumber.value--;
      return;
    }
  }
  state.goodsImageList.push('/' + response.key);
}

/* 规格图片上传成功 */
const handleSpecImgSuccess = (row) => {
  return (response, file, fileList, e) => {
    for (let i = 0; i < mallGoodsForm.sku_list.length; i++) {
      if (
        mallGoodsForm.sku_list[i].goods_sku_id === row.goods_sku_id
      ) {
        mallGoodsForm.sku_list[i].image = '/' + response.key;
        break;
      }
    }
  };
}

/* 上传图片前先校验图片大小
        此处可用于获取上传凭证
    */
const beforeAvatarUpload = (file) => {
  if (file.type === '') {
    ElMessage.warning(`请上传有后缀的图片,或添加图片的后缀`);
    return false;
  }
  const suffix = file.type.split('/')[1];
  if (['image/tiff'].includes(file.type)) {
    ElMessage.warning(`暂不支tiff该格式的图片上传!`);
    return false;
  }
  if (['video/mp4', 'video/avi', 'video/quicktime'].includes(file.type)) {
    ElMessage.warning('请上传图片!');
    return false;
  }
  tempGoodsImageNumber.value++;
  const isLt150K = file.size / 1024 < 150;
  formLoading.value = true;
  disabledbtn.value = true;
  if (!isLt150K) {
    tempGoodsImageNumber.value--;
    setTimeout(() => {
      /* 解决提示信息重叠问题 */
      ElMessage.warning('上传图片大小不能超过150k,请压缩后再上传!');
    }, 100);
    formLoading.value = false;
    disabledbtn.value = false;
    return false;
  }
  if (state.goodsImageList.length >= 5 || tempGoodsImageNumber.value > 5) {
    tempGoodsImageNumber.value--;
    setTimeout(() => {
      /* 解决提示信息重叠问题 */
      ElMessage.warning('你无法继续上传，上传图片数量不超过5张！');
    }, 100);
    formLoading.value = false;
    disabledbtn.value = false;
    return false;
  }
  return getUploadToken(suffix);
}
/* 上传图片before */
const beforeAvatarUploadImg = (file) => {
  const isLt200K = file.size / 1024 < 200;
  if (!isLt200K) {
    ElMessage.warning('上传图片大小不能超过200K,请压缩后再上传!');
    return false;
  }
  const suffix = file.type.split('/')[1];
  return getUploadToken(suffix);
}
/* 获取七牛云token */
const getUploadToken = (suffix) => {
  return Request.getUploadToken({ suffix })
    .then((res) => {
      uploadData.token = res.result.upToken;
      uploadData.key = res.result.fileName[0];
    })
    .catch((res) => { });
}

/* 获取商品状态的对象 */
const handleStateObj = (data) => {
  for (const item of data) {
    statusObj[item.dictValue] = item.dictLabel;
  }
}

/* 获取表格信息 */
getTableInfo();
/* 获取运费模板信息 */
getListDataInfo('getMallDeliverInfo', state, 'selectFreighTemplateList');
/* 获取 商品分类数据 */
getListDataInfo('getMallCategoryInfo', state, 'selectCategoriesList');
/* 初始化请求类型，广告位置信息 */
getDictDataInfo('GOODS_TYPE', state, 'selectStatusList', handleStateObj);
getDictDataInfo('WHETHER', state, 'selectWhetherListSearch');
getDictDataInfo('PLATFORM_TYPE', state, 'selectPlatformList');

onBeforeUnmount(() => {
  handleDestroyEditor();
})
</script>

<style lang="scss" scoped>
/* layout-布局 */
.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.cyan {
  color: #67c23a;
}

.orange {
  color: #e6a23c;
}

.mr10 {
  margin-right: 10px;
}

.textAlignCenter {
  text-align: center;
}

/* 修改select的盒模型 */
.el-select {
  display: block;
}

/* 确定按钮的显示与隐藏 */
.displaybtn {
  display: none;
}

/* 修改该属性值  查询条件，查询结果得样式 */
.el-breadcrumb {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

/* 提示图标设置 */
.icon-wzg-config {
  height: 30px;
  line-height: 30px;
}

/* 修改Switch开关 */
.el-switch {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}

/* 修改显示图片宽高 ,>>>用于修改组件中的css样式*/
:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 148px;
  height: 148px;
}

/* 分割线字前的蓝色 start*/
.title-left-color {
  color: #666;
  font-size: 16px;
  font-weight: 550;
}

.title-left-color::before {
  content: '';
  position: absolute;
  width: 4px;
  height: 15px;
  background: #00aeff;
  top: 3px;
  left: 10px;
}

/* end */

.w-tag .el-tag {
  margin: 2px 5px;
}

#editor {
  width: 397px;
}

/* 图片上传 start */
.w-img-upload {
  display: inline;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

:deep(.el-upload--text) {
  width: inherit;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

/* 图片上传 end */

.wzg-continer-video {
  display: inline-block;
  position: relative;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

/* 视频删除按钮 start*/
.wzg-video:hover {
  opacity: 0.8;
}

.wzg-video {
  background-color: #fff;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}

.w-video-del {
  display: none;
}

.wzg-continer-video:hover .w-video-del {
  position: absolute;
  top: 50%;
  left: 50%;
  z-index: 1000;
  display: flex;
  width: 28px;
  height: 28px;
  padding: 6px;
  cursor: pointer;
  background-color: rgba(0, 0, 0, 0.5);
  font-size: 18px;
  color: #fff;
  border-radius: 5px;
  transform: translate(-50%, -50%);
}

/* 视频删除按钮 end*/

/* 解决图片弹窗，没有覆盖富文本框问题 start */
.goods-detail :deep(.el-form-item__content) {
  z-index: 100;
}

/* end */

/* tag相关 start */
.ibDraggable {
  display: inline-block;
  // margin: 0 10px 10px 0;
  margin-right: 10px;
}

/* .el-tag {
  margin: 0 0 10px 10px;
} */
.button-new-tag {
  height: 28px;
  line-height: 28px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
}

/* end */

.w-icon-close {
  margin-left: 10px;
  font-size: 18px;
  color: #ababab;
  cursor: pointer;
}

.w-icon-close:hover {
  color: #6b6b6b;
}

/* 规格图片 */
/* 图片上传 start */
.w-spec .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.w-spec :deep(.el-upload--text) {
  width: inherit;
}

.w-spec .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.w-spec .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.w-spec .avatar-uploader-icon.small {
  width: 78px;
  height: 78px;
  line-height: 78px;
}

.w-spec .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.w-spec .avatar-uploader :deep(.el-upload--text) {
  height: inherit;
  padding: 2px 2px;
  color: #409eff;
}

.w-spec .wzg-continer-img {
  position: relative;
  display: inline-block;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;

  .wzg-img {
    width: inherit;
    height: inherit;
  }

  .el-icon-close {
    display: none;
  }
}

.w-spec .wzg-continer-img.small {
  width: 78px;
  height: 78px;
  line-height: 78px;
}

/* 规格删除按钮 start*/
.wzg-continer-img:hover .el-icon-close {
  position: absolute;
  top: 1px;
  right: -1px;
  z-index: 1000;
  display: inline-block;
  width: 24px;
  height: 24px;
  padding: 5px;
  cursor: pointer;
  background-color: rgba($color: #f00, $alpha: 0.8);
  color: #fff;
  border-radius: 2px;
  transition: 0.5s;
}

.w-spec .el-icon-close:hover,
.w-spec .wzg-video:hover {
  opacity: 0.8;
}

.w-spec .wzg-video {
  background-color: #fff;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}

/* 图片列表 */
.w-img-list {
  position: relative;
  overflow: hidden;
  width: 148px;
  height: 148px;
  display: inline-block;
  margin: 0 8px 8px 0;
  border-radius: 6px;
  border: 1px solid #c0ccda;

  .w-img {
    width: 148px;
    height: 148px;
  }
}

.w-img-list:hover .w-icon {
  position: absolute;
  display: flex;
  justify-content: space-between;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  .w-look-icon {
    margin-right: 10px;
  }

  .w-look-icon,
  .w-del-icon {
    padding: 6px;
    cursor: pointer;
    background-color: rgba(0, 0, 0, 0.5);
    font-size: 24px;
    color: #fff;
    border-radius: 5px;
  }
}
</style>
